# coding = utf8

# replace common dict for better caching
class NewDict:
    def __init__(self, filename = ''):
        self.m_dict = {}
        self.m_filename = ''
        self.m_defaultVal = 0
        if len(filename) > 0:
            self.m_filename = filename
            self.load_from_file()

    def set_default(self, default):
        self.m_defaultVal = default

    def load_from_file(self):
        assert len(self.m_filename) > 0
        _fin = open(self.m_filename, 'r')
        content = _fin.readline()
        while content:
            ss = content.rstrip().split()
            if len(ss) == 2:
                self.insert(ss[0], ss[1])
            if len(ss) == 1:
                self.insert(ss[0], self.m_defaultVal)
        _fin.close()

    # return value is whether our dict has already haven the key
    def insert(self, key, val):
        res = True
        if self.m_dict.has_key(key):
            res = False
        self.m_dict[key] = val
        return res

    def get_val(self, key, put=False):
        if self.m_dict.has_key(key):
            return self.m_dict[key]
        if put:
            self.insert(key, self.m_defaultVal)
        return self.m_defaultVal

    def add_val(self, key, val):
        if key in self.m_dict:
            self.m_dict[key] += val
            return True
        else:
            self.m_dict[key] = val
            return False

    def fill_val(self, val):
        for key in self.m_dict:
            self.m_dict[key] = val

    def keys(self):
        return self.m_dict.keys()

    def __getitem__(self, key):
        return self.m_dict[key]

    def __setitem__(self, key, value):
        self.m_dict[key] = value

    def items(self):
        return self.m_dict.items()
    def values(self):
        return self.m_dict.values()
    def keys(self):
        return self.m_dict.keys()

    def get_highest_key(self):
        best_val = 0
        best_key = False
        for item in self.m_dict.items():
            if item[1] > best_val:
                best_key = item[0]
                best_val = item[1]
        return best_key


    def has_key(self, key):
        return self.m_dict.has_key(key)

    def print_file(self, filename = ''):
        assert len(filename) > 0 or len(self.m_filename) > 0
        _fn = filename
        if len(_fn) == 0: _fn = self.m_filename
        _fout = open(_fn, 'w')
        sorted_item = sorted(self.m_dict.items(), key=lambda e:e[1], reverse=True)
        for (key, val) in sorted_item:
            _fout.write(str(key) + '\t' + str(val) + '\n')
        _fout.close()

